﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeadMaster.Models;
using LeadMaster.DAL;
using LeadMaster.ViewModels;
using LeadMaster.Helpers;

namespace LeadMaster.Controllers
{
    public class LeadBuilderController : Controller
    {
        private DunsmoreContext db = new DunsmoreContext();

        SelectList AnswerTypes = new SelectList(new[]
                                          {
                                              new {ID="C",Name="Characters"},
                                              new{ID="L",Name="Logic"},
                                              new{ID="I",Name="Numeric Range"},
                                          },
                            "ID", "Name", 1);

        public ActionResult Index()
        {
            Maintenance.inMaintenance = true;
            IEnumerable<LeadTemplate> leadTemplate = db.LeadTemplate;
            return View(leadTemplate);
        }

        //
        // GET: /LeadBuilder/Details/5

        public ActionResult Details(int id = 0)
        {
            LeadTemplate leadtemplate = db.LeadTemplate.Find(id);
            if (leadtemplate == null)
            {
                return HttpNotFound();
            }
            return View(leadtemplate);
        }

        public ActionResult Create()
        {
          ViewModelLeadBuilder viewModel = new ViewModelLeadBuilder();
          viewModel.AllSectors = db.Sectors.ToList();
          ViewBag.LeadTemplate_SectorID = new SelectList(db.Sectors, "SectorID", "Sector");
          viewModel.LeadTemplate = new LeadTemplate();
          return View();
        }

        public ActionResult AddLeadStat(int id)
        {
          LeadStat leadStat = new LeadStat();
          LeadTemplate leadTemplate = db.LeadTemplate.Find(id);
          leadStat.LeadTemplateID = leadTemplate.LeadTemplateID;
          leadStat.DisplayOrder = db.LeadStat.Where(m => m.LeadTemplateID == id).Count() + 1;
          return PartialView("AddLeadStat",leadStat);
        }

        [HttpPost]
        public ActionResult AddLeadStat(LeadStat leadStat)
        {
          if (ModelState.IsValid)
          {
            db.LeadStat.Add(leadStat);
            db.SaveChanges();
          }
          return RedirectToAction("ShowLeadStat", new { id = leadStat.LeadTemplateID });
        }

        public ActionResult ShowLeadStat(int id)
        {
          List<LeadStat> leadStats = db.LeadStat.Where(m => m.LeadTemplateID == id).OrderBy(m => m.DisplayOrder).ToList();

          return PartialView(leadStats);
        }

        public ActionResult ShowLeadGroups(int id)
        {
          List<LeadGroups> leadGroups = db.LeadGroups.Where(m => m.LeadTemplateID == id).OrderBy(m => m.DisplayOrder).ToList();

          return PartialView(leadGroups);
        }

        public ActionResult ShowStatQuestions(int id)
        {
          List<LeadStatQuestions> leadStatQuestions = db.LeadStatQuestions.Where(m => m.LeadStatID == id).OrderBy(m => m.DisplayOrder).ToList();
          ViewBag.LeadStatId = id;
          return PartialView(leadStatQuestions);
        }

        public ActionResult ShowGroupQuestions(int id)
        {
          List<LeadGroupQuestions> leadGroupQuestions = db.LeadGroupQuestions.Where(m => m.LeadGroupsID == id).OrderBy(m => m.DisplayOrder).ToList();
          ViewBag.LeadGroupId = id;
          return PartialView(leadGroupQuestions);
        }

        public ActionResult Test()
        {
          List<LeadGroupQuestions> leadGroupQuestions;
          try
          {
            leadGroupQuestions = db.LeadGroupQuestions.Where(m => m.LeadGroupsID == 1).ToList();
            ViewBag.LeadGroupId = 1;
          }
          catch (Exception e)
          {
            ViewBag.ErrorMessage = "Create Lead " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
            return View("ErrorMessages");
          }
          return PartialView(leadGroupQuestions);
        }

        public ActionResult CreateStatQuestions(int id)
        {
          LeadStatQuestions leadStatQuestion = new LeadStatQuestions();
          leadStatQuestion.LeadStatID = id;
          SelectList answerTypeList = this.AnswerTypes;
          ViewBag.AnswerType = answerTypeList;
          leadStatQuestion.DisplayOrder = db.LeadStatQuestions.Where(m => m.LeadStatID == id).Count() + 1;
          leadStatQuestion.DropDown = false;
          return PartialView(leadStatQuestion);
        }

        [HttpPost]
        public ActionResult CreateStatQuestions(LeadStatQuestions leadStatQuestion)
        {
          if (ModelState.IsValid)
          {
            leadStatQuestion.AcceptedAnswerDateFrom = DateTime.Now;
            leadStatQuestion.AcceptedAnswerDateTo = DateTime.Now;
            db.LeadStatQuestions.Add(leadStatQuestion);
            db.SaveChanges();
            return RedirectToAction("ShowStatQuestions", new { id = leadStatQuestion.LeadStatID });
          }

          return RedirectToAction("ShowStatQuestions", new { id=leadStatQuestion.LeadStatID});
        }

        public ActionResult CreateGroupQuestions(int id)
        {
          LeadGroupQuestions leadGroupQuestion = new LeadGroupQuestions();
          leadGroupQuestion.LeadGroupsID = id;
          SelectList answerTypeList = this.AnswerTypes;
          ViewBag.AnswerType = answerTypeList;
          leadGroupQuestion.DisplayOrder = db.LeadGroupQuestions.Where(m => m.LeadGroupsID == id).Count()+1;
          return PartialView(leadGroupQuestion);
        }

        [HttpPost]
        public ActionResult CreateGroupQuestions(LeadGroupQuestions leadGroupQuestion)
        {
          if (ModelState.IsValid)
          {
            leadGroupQuestion.AcceptedAnswerDateFrom = DateTime.Now;
            leadGroupQuestion.AcceptedAnswerDateTo = DateTime.Now;
            db.LeadGroupQuestions.Add(leadGroupQuestion);
            db.SaveChanges();
            return RedirectToAction("ShowGroupQuestions", new { id = leadGroupQuestion.LeadGroupsID });
          }

          return RedirectToAction("ShowGroupQuestions", new { id = leadGroupQuestion.LeadGroupsID });
        }

        public ActionResult EditGroupQuestion(int id)
        {
          LeadGroupQuestions leadGroupQuestion = db.LeadGroupQuestions.Find(id);
          SelectList answerTypeList = this.AnswerTypes;
          ViewBag.answerTypeList = answerTypeList;
          return PartialView(leadGroupQuestion);
        }

        [HttpPost]
        public ActionResult EditGroupQuestion(LeadGroupQuestions leadGroupQuestion)
        {
          if (ModelState.IsValid)
          {
            leadGroupQuestion.AcceptedAnswerDateFrom = DateTime.Now;
            leadGroupQuestion.AcceptedAnswerDateTo = DateTime.Now;
            db.Entry(leadGroupQuestion).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("ShowGroupQuestions", new { id = leadGroupQuestion.LeadGroupsID });
          }

          return RedirectToAction("ShowGroupQuestions", new { id = leadGroupQuestion.LeadGroupsID });
        }

        public ActionResult EditStatQuestion(int id)
        {
          LeadStatQuestions leadStatQuestion = db.LeadStatQuestions.Find(id);
          SelectList answerTypeList = this.AnswerTypes;
          ViewBag.answerTypeList = answerTypeList;
          return PartialView(leadStatQuestion);
        }

        [HttpPost]
        public ActionResult EditStatQuestion(LeadStatQuestions leadStatQuestion)
        {
          if (ModelState.IsValid)
          {
            bool moveDisplayOrder=false;
            if (db.LeadStatQuestions
              .Any(m => m.LeadStatID==leadStatQuestion.LeadStatID && m.DisplayOrder==leadStatQuestion.DisplayOrder 
                && m.LeadStatQuestionsID!=leadStatQuestion.LeadStatQuestionsID))
            {
              moveDisplayOrder = true;
            }
            leadStatQuestion.AcceptedAnswerDateFrom = DateTime.Now;
            leadStatQuestion.AcceptedAnswerDateTo = DateTime.Now;
            db.Entry(leadStatQuestion).State = EntityState.Modified;
            if (moveDisplayOrder)
            {
              // however, we need to shift display orders for other stat questions
              foreach (LeadStatQuestions item in db.LeadStatQuestions.Where(m => m.LeadStatQuestionsID!=leadStatQuestion.LeadStatQuestionsID && m.LeadStatID==leadStatQuestion.LeadStatID && m.DisplayOrder>=leadStatQuestion.DisplayOrder).ToList())
              {
                item.DisplayOrder++;
                db.Entry(item).State = EntityState.Modified;
              }
            }

            db.SaveChanges();
            return RedirectToAction("ShowStatQuestions", new { id = leadStatQuestion.LeadStatID });
          }

          return RedirectToAction("ShowStatQuestions", new { id = leadStatQuestion.LeadStatID });
        }

        public ActionResult EditLeadStat(int id)
        {
          LeadStat leadStat = db.LeadStat.Find(id);
          return PartialView(leadStat);
        }

        [HttpPost]
        public ActionResult EditLeadStat(LeadStat leadStat)
        {
          if (ModelState.IsValid)
          {
            db.Entry(leadStat).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("ShowLeadStat", new { id = leadStat.LeadTemplateID});
          }

          return RedirectToAction("ShowLeadStat", new { id = leadStat.LeadTemplateID });
        }

        public ActionResult EditLeadGroup(int id)
        {
          LeadGroups leadGroup = db.LeadGroups.Find(id);
          return PartialView(leadGroup);
        }

        [HttpPost]
        public ActionResult EditLeadGroup(LeadGroups leadGroup)
        {
          if (ModelState.IsValid)
          {
            db.Entry(leadGroup).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("ShowLeadGroups", new { id = leadGroup.LeadTemplateID });
          }

          return RedirectToAction("ShowLeadGroups", new { id = leadGroup.LeadTemplateID });
        }

        public ActionResult DeleteGroupQuestion(int id)
        {
          LeadGroupQuestions leadGroupQuestion = db.LeadGroupQuestions.Find(id);
          db.LeadGroupQuestions.Remove(leadGroupQuestion);
          try
          {
            db.SaveChanges();
          }
          catch (Exception e)
          {
            if (e.InnerException.InnerException.ToString().Contains("The DELETE statement conflicted with the REFERENCE constraint"))
            {
            ViewBag.FriendlyMessage = "You can not delete this question because it is already involved in a set of Results. " ;
            ViewBag.FriendlyMessage += "It would be best to Clone this Template and apply a version number to it.";
            }
            ViewBag.ErrorMessage = e.InnerException;
            return View("ErrorMessages");
          }
          return RedirectToAction("ShowGroupQuestions", new { id=leadGroupQuestion.LeadGroupsID});
        }

        public ActionResult DeleteStatQuestion(int id)
        {
          LeadStatQuestions leadStatQuestion = db.LeadStatQuestions.Find(id);
          db.LeadStatQuestions.Remove(leadStatQuestion);
          try
          {
            db.SaveChanges();
          }
          catch (Exception)
          {
          }
         
          return RedirectToAction("ShowStatQuestions", new { id = leadStatQuestion.LeadStatID });
        }

        public ActionResult DeleteGroupSectionQuestion(int id)
        {
          LeadGroups leadGroup = db.LeadGroups.Find(id);
          db.LeadGroups.Remove(leadGroup);
          try
          {
            db.SaveChanges();
          }
          catch (Exception)
          {
            
            
          }
          return RedirectToAction("ShowLeadGroups", new { id = leadGroup.LeadTemplateID });
        }

        public ActionResult DeleteStatSectionQuestion(int id)
        {
          LeadStat leadStat = db.LeadStat.Find(id);
          db.LeadStat.Remove(leadStat);
          db.SaveChanges();
          return RedirectToAction("ShowLeadStat", new { id = leadStat.LeadTemplateID });
        }

        public ActionResult AddLeadGroup(int id)
        {
          LeadGroups leadGroup = new LeadGroups();
          LeadTemplate leadTemplate = db.LeadTemplate.Find(id);
          leadGroup.LeadTemplateID = leadTemplate.LeadTemplateID;
          leadGroup.DisplayOrder = db.LeadGroups.Where(m => m.LeadTemplateID == id).Count() + 1;

          return PartialView("AddLeadGroup", leadGroup);
        }

        [HttpPost]
        public ActionResult AddLeadGroup(LeadGroups leadGroup)
        {
          if (ModelState.IsValid)
          {
            db.LeadGroups.Add(leadGroup);
            db.SaveChanges();
          }
          return RedirectToAction("ShowLeadGroups", new { id=leadGroup.LeadTemplateID});
        }


        [HttpPost]
        public ActionResult Create(ViewModelLeadBuilder viewModel)
        {
            if (ModelState.IsValid)
            {
                db.LeadTemplate.Add(viewModel.LeadTemplate);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(viewModel);
        }

        public ActionResult Edit(int id = 0)
        {
            ViewModelLeadBuilder viewModel = new ViewModelLeadBuilder();
            viewModel.LeadTemplate = db.LeadTemplate.Find(id);
            ViewBag.LeadTemplate_SectorID = new SelectList(db.Sectors, "SectorID", "Sector", viewModel.LeadTemplate.SectorID);

            if (viewModel.LeadTemplate == null)
            {
                return HttpNotFound();
            }
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Edit(LeadTemplate leadtemplate)
        {
            if (ModelState.IsValid)
            {
                db.Entry(leadtemplate).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(leadtemplate);
        }

        //
        // GET: /LeadBuilder/Delete/5

        public ActionResult Delete(int id = 0)
        {
            LeadTemplate leadtemplate = db.LeadTemplate.Find(id);
            if (leadtemplate == null)
            {
                return HttpNotFound();
            }
            return View(leadtemplate);
        }

        //
        // POST: /LeadBuilder/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            LeadTemplate leadtemplate = db.LeadTemplate.Find(id);
            db.LeadTemplate.Remove(leadtemplate);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult Clone(int id)
        {
          LeadTemplate leadTemplate = db.LeadTemplate.Find(id);
          if (leadTemplate!=null)
          {
            LeadTemplate newLeadTemplate = new LeadTemplate();
            newLeadTemplate.SectorID = leadTemplate.SectorID;
            newLeadTemplate.Title = "Copy of " + leadTemplate.Title;
            newLeadTemplate.LinkedGroupSets = leadTemplate.LinkedGroupSets;
            db.LeadTemplate.Add(newLeadTemplate);
            db.SaveChanges();
            // Lead Stats
            foreach (var item in db.LeadStat.Where(m => m.LeadTemplateID == leadTemplate.LeadTemplateID).ToList())
            {
              LeadStat newLeadStat = new LeadStat();
              newLeadStat.LeadTemplateID = newLeadTemplate.LeadTemplateID;
              newLeadStat.Title = item.Title;
              newLeadStat.DisplayOrder = item.DisplayOrder;
              newLeadStat.Notes = item.Notes;
              newLeadStat.QuestionOrder = item.QuestionOrder;
              newLeadStat.BackgroundColour = item.BackgroundColour;
              db.LeadStat.Add(newLeadStat);
              db.SaveChanges();
              // Stat Questions
              foreach (var statquestion in db.LeadStatQuestions.Where(m => m.LeadStatID==item.LeadStatID).ToList())
              {
                LeadStatQuestions newLeadStatQuestions = new LeadStatQuestions();
                newLeadStatQuestions.LeadStatID = newLeadStat.LeadStatID;
                newLeadStatQuestions.Question = statquestion.Question;
                newLeadStatQuestions.AnswerType = statquestion.AnswerType;
                newLeadStatQuestions.AcceptedAnswerChar = statquestion.AcceptedAnswerChar;
                newLeadStatQuestions.AcceptedAnswerBool = statquestion.AcceptedAnswerBool;
                newLeadStatQuestions.AcceptedAnswerDateFrom = statquestion.AcceptedAnswerDateFrom;
                newLeadStatQuestions.AcceptedAnswerDateTo = statquestion.AcceptedAnswerDateTo;
                newLeadStatQuestions.Mandatory = statquestion.Mandatory;
                newLeadStatQuestions.AcceptedAnswerIntFrom = statquestion.AcceptedAnswerIntFrom;
                newLeadStatQuestions.AcceptedAnswerIntTo = statquestion.AcceptedAnswerIntTo;
                newLeadStatQuestions.DisplayOrder = statquestion.DisplayOrder;
                newLeadStatQuestions.Notes = statquestion.Notes;
                newLeadStatQuestions.DropDown = statquestion.DropDown;
                db.LeadStatQuestions.Add(newLeadStatQuestions);
              }
            }
            // Group Stats
            foreach (var item in db.LeadGroups.Where(m => m.LeadTemplateID == leadTemplate.LeadTemplateID).ToList())
            {
              LeadGroups newLeadGroup = new LeadGroups();
              newLeadGroup.LeadTemplateID = newLeadTemplate.LeadTemplateID;
              newLeadGroup.Title = item.Title;
              newLeadGroup.DisplayOrder = item.DisplayOrder;
              newLeadGroup.Notes = item.Notes;
              newLeadGroup.QualifyingGroup = item.QualifyingGroup;
              newLeadGroup.MinMandatoryPrimary = item.MinMandatoryPrimary;
              newLeadGroup.MinMandatorySecondary = item.MinMandatorySecondary;
              newLeadGroup.QuestionOrder = item.QuestionOrder;
              newLeadGroup.BackgroundColour = item.BackgroundColour;
              db.LeadGroups.Add(newLeadGroup);
              db.SaveChanges();
              // Stat Questions
              foreach (var groupquestion in db.LeadGroupQuestions.Where(m => m.LeadGroupsID == item.LeadGroupsID).ToList())
              {
                LeadGroupQuestions newLeadGroupQuestions = new LeadGroupQuestions();
                newLeadGroupQuestions.LeadGroupsID = newLeadGroup.LeadGroupsID;
                newLeadGroupQuestions.Question = groupquestion.Question;
                newLeadGroupQuestions.AnswerType = groupquestion.AnswerType;
                newLeadGroupQuestions.AcceptedAnswerChar = groupquestion.AcceptedAnswerChar;
                newLeadGroupQuestions.AcceptedAnswerBool = groupquestion.AcceptedAnswerBool;
                newLeadGroupQuestions.AcceptedAnswerDateFrom = groupquestion.AcceptedAnswerDateFrom;
                newLeadGroupQuestions.AcceptedAnswerDateTo = groupquestion.AcceptedAnswerDateTo;
                newLeadGroupQuestions.Mandatory = groupquestion.Mandatory;
                newLeadGroupQuestions.AcceptedAnswerIntFrom = groupquestion.AcceptedAnswerIntFrom;
                newLeadGroupQuestions.AcceptedAnswerIntTo = groupquestion.AcceptedAnswerIntTo;
                newLeadGroupQuestions.PrimarySecondary = groupquestion.PrimarySecondary;
                newLeadGroupQuestions.DisplayOrder = groupquestion.DisplayOrder;
                newLeadGroupQuestions.Notes = groupquestion.Notes;
                newLeadGroupQuestions.DropDown = groupquestion.DropDown;
                db.LeadGroupQuestions.Add(newLeadGroupQuestions);
              }
            }
            db.SaveChanges();
          }
          return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

      public ActionResult PreviewQuestionnaire(string templateTitle)
      {

        ViewModelOutsourcer ViewModel=new ViewModelOutsourcer();

        ViewModel.Leads=db.Leads.FirstOrDefault();
        ViewModel.Leads.LeadTemplateID=db.LeadTemplate.Where(m => m.Title==templateTitle).FirstOrDefault().LeadTemplateID;

        ViewModel.LeadClient = ViewModel.Leads.LeadID;

        ViewModel.PreviewMode = true;

        OutsourcerController outsourcerController = new OutsourcerController();

        ViewModel = outsourcerController.ProcessQuestionnaire(ViewModel, true);


        return View("../Outsourcer/Questionnaire", ViewModel);
      }
    }
}